import 'package:flutter/material.dart';
import 'package:loading/indicator/ball_spin_fade_loader_indicator.dart';
import 'package:loading/loading.dart';

import 'event_bus.dart';

class NetworkLoading extends StatefulWidget {
  NetworkLoading({Key key, this.child}) : super(key: key);

  final Widget child;

  @override
  State<StatefulWidget> createState() {
    return NetworkLoadingState();
  }
}

class NetworkLoadingState extends State<NetworkLoading> {
  bool _loading=true;
  @override
  void initState() {
    eventBus.on<LoadingEvent>().listen((event) {
      if(mounted){
        if(event.status&&!_loading){
          Future.delayed(Duration(seconds: 2), (){
            setState(() {
              _loading = event.status;
            });
          });
        }else{
          setState(() {
            _loading = event.status;
          });
        }
      }

    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          widget.child,
          Offstage(
              offstage: _loading,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                color: Colors.transparent,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Loading(indicator: BallSpinFadeLoaderIndicator(),color: Colors.orange,),
                  ],
                ),
              )
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
